package base.day03;

/**
 * 描述：
 *      数组结构实现大小固定的队列和栈
 * @author hl
 * @version 1.0
 * @date 2020/10/25 14:42
 */
public class Code_02_Array_to_Stack_Queue {

    public static class ArrayStack{
        private Integer[] arr;
        private Integer index;

        public ArrayStack(int size){
            if (size < 0) {
                throw new IllegalArgumentException("the size is less than 0");
            }
            arr = new Integer[size];
            index = 0;
        }

        public void push(Integer num){
            if (index == arr.length) {
                throw new ArrayIndexOutOfBoundsException("栈已满~");
            }
            arr[index++] = num;
        }

        public Integer pop(){
            if (index == 0) {
                throw new ArrayIndexOutOfBoundsException("栈为空~");
            }
            return arr[--index];
        }

        public Integer peek(){
            if (index == 0) {
                return null;
            }
            return arr[index - 1];
        }
    }
    public static class ArrayQueue{
        private Integer[] arr;
        private int start;
        private int end;
        private int size;

        public  ArrayQueue(int initSize){
            arr = new  Integer[initSize];
            start = 0;
            end = 0;
            size = 0;
        }

        public void push(int obj){
            if (size == arr.length) {
                throw new IllegalArgumentException("队列已满~");
            }
            size++;
            end = end == arr.length ? 0 : end;//循环利用数组
            arr[end++] = obj;
        }
        public Integer poll(){
            if (size == 0) {
                throw new IllegalArgumentException("队列为空~");
            }
            size--;
            int temp = arr[start++];
            start = start == arr.length ? 0 : start;
            return temp;
        }
        public Integer peek(){
            if(size == 0){
                return null;
            }
            return arr[start];
        }
    }

    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(3);
        arrayQueue.push(1);
        arrayQueue.push(2);
        arrayQueue.push(3);
        System.out.println(arrayQueue.poll());
        System.out.println(arrayQueue.poll());
        System.out.println(arrayQueue.peek());
        System.out.println(arrayQueue.poll());
        System.out.println(arrayQueue.peek());
    }
}
